package com.ax.center.urils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author zy
 * @date 2023/7/10 10:17
 */
public class FileUploadUtil {
    @Value("${aliyun.oss.endpoint}")
    private static String ossEndpoint;
    @Value("${aliyun.oss.accessKey}")
    private static   String ossAccessKey;
    @Value("${aliyun.oss.secretKey}")
    private static String ossSecretKey;
    @Value("${aliyun.oss.bucketName}")
    private static String ossBucketName;
    public static String uploadFile(MultipartFile file) throws IOException {
        // 创建 OSS 客户端
        OSS ossClient = new OSSClientBuilder().build(ossEndpoint, ossAccessKey, ossSecretKey);

        try {
            // 生成唯一的文件名
            String fileName = generateFileName(file.getOriginalFilename());

            // 设置上传文件的元信息
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());

            // 上传文件到 OSS
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(ossBucketName, fileName, inputStream, metadata);

            // 返回文件访问路径
            return getFileUrl(ossEndpoint, ossBucketName, fileName);
        } finally {
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }
    }

    // 生成唯一的文件名
    private static String generateFileName(String originalFilename) {
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        return UUID.randomUUID().toString() + extension;
    }

    // 获取文件访问路径
    private static String getFileUrl(String endpoint, String bucketName, String fileName) {
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}
